package services

import (
	"fmt"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_live"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
	"time"

	"github.com/spf13/cast"

	"longmen/server/pkg/common/api_models"
	//pb "longmen/server/websocket_grpc/protobuf"
)

func calculateUserLevel(point uint32) ([]*models_main.UserLevelRule, uint8, error) {
	var (
		err   error
		level uint8
		fName = "CalculateUserLevel"
		rule  []*models_main.UserLevelRule
	)

	level = 1

	if rule, err = cache.GetUserLevelRule(); err != nil {
		return nil, 0, fmt.Errorf("%s %s", utils2.Convert(fName), err.Error())
	}

	for i := 0; i < len(rule)-1; i++ {
		for j := 0; j < len(rule)-1-i; j++ {
			if rule[j].Level > rule[j+1].Level {
				rule[j], rule[j+1] = rule[j+1], rule[j]
			}
		}
	}

	for i := 0; i < len(rule); i++ {
		if point >= rule[i].Point {
			level = rule[i].Level
		} else {
			break
		}
	}

	return rule, level, nil
}

func GetUserLevel(userPoint int) (*api_models.Level, error) {
	fName := "GetUserLevel"
	var upgradePoint uint32 //指定等级所需经验
	var process uint32      //当前等级进度
	var difference uint32   //获取用户经验值,计算出level
	var remainder uint32    //获取用户经验值,计算出level
	rule, level, err := calculateUserLevel(uint32(userPoint))
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err)
	}

	for i := 0; i < len(rule); i++ {
		if level == rule[i].Level-1 {
			upgradePoint = rule[i].Point
			if i > 0 {
				process = uint32(userPoint - int(rule[i-1].Point))
				difference = rule[i].Point - rule[i-1].Point
				break
			}
			process = uint32(userPoint) //0级别
			difference = rule[i].Point
			break
		}
	}

	if upgradePoint > uint32(userPoint) {
		remainder = upgradePoint - uint32(userPoint)
	}

	return &api_models.Level{
		Level:        level,
		Point:        uint32(userPoint),
		UpgradePoint: upgradePoint,
		Process:      process,
		Difference:   difference,
		Remainder:    remainder,
	}, nil
}

// 进聊天室时得用户的信息，是不是房管，贵族等级
func ChatRoomGetUserInfo(req *api_models.UserInfoReq) (*api_models.UserInfoResp, error) {
	idString := cast.ToString(req.Uid)
	// id 長度大於10，表示是未登入的遊客
	if len(idString) > 10 {
		return &api_models.UserInfoResp{Permit: 2}, nil
	}

	result, err := cache.GetUserFullInfo(int(req.Uid))
	if err != nil {
		return &api_models.UserInfoResp{Permit: 2}, nil
	}

	var permit = 1

	if int64(req.Uid) != req.AnchorId {
		managerUser, err := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": req.Uid})
		if err != nil {
			permit = 2
		}
		if managerUser.Id < 1 {
			permit = 2
		}
		if managerUser.Anchorid != 0 && managerUser.Anchorid != int(req.AnchorId) { //不是超管和该房间管理
			permit = 2
		}
	}
	//fixme 注释以下语句
	//vipLevel := getNobleId(uint(req.GetUid()))
	propsItem := db_main.GetProps(uint64(req.Uid))
	//oUserInfo := &models_main.UserInfo{}
	//mysql.GetXAnyParam(oUserInfo, map[string]interface{}{"uid": req.Uid}, false, fName)

	var level uint8
	userLevel, err := GetUserLevel(result.Point)
	if err == nil && userLevel != nil {
		level = userLevel.Level
	}

	// cache.SetUserInfoCache(int(req.GetUid()), api_models.UserCacheInfo{NickName: result.NickName, Avatar: result.Avatar, Vip: vipLevel})
	return &api_models.UserInfoResp{
		NickName: result.NickName,
		Level:    int32(level),
		//Vip:      int32(vipLevel),
		Vip:           propsItem.NobleId,
		Avatar:        result.Avatar,
		Permit:        int32(permit),
		ImmeGift:      0,
		LoginPlatform: result.LoginPlatform,
		LastLoginTime: result.LastLogin.Unix(),
	}, nil
}

// 道具列表
func GetPorosList() (*api_models.PropsResp, error) {
	params := make(map[string]interface{})
	params["status"] = 1
	props, err := db_main.GetPropsParam(params, "weight DESC")
	if err != nil {
		return nil, err
	}
	propsList := []*api_models.PropsList{}
	for _, v := range props {
		propsList = append(propsList, &api_models.PropsList{
			Id:    int32(v.Id),
			Name:  v.Name,
			Icon:  v.Icon,
			Type:  int32(v.Type),
			Style: v.Style,
		})
	}
	return &api_models.PropsResp{
		PropsList: propsList,
	}, nil
}

// 背包
func GetUserBackpack(req *api_models.UserBackpackReq) (*api_models.UserBackpackResp, error) {
	var userBackPack []*api_models.UserBackpack
	list, err := db_main.GetUserBackpacksParam(map[string]interface{}{"uid": req.Uid, "used": 0, "selected": 1}, "", 0, 0)
	if err != nil {
		return nil, err
	}
	tm := time.Now().Unix()
	for _, v := range list {
		flag := false
		for _, l := range userBackPack {
			if l.Gid == int32(v.Gid) && v.ExpTime >= tm && v.EffTime < tm {
				l.Num++
				flag = true
			}
		}
		if !flag {
			userBackPack = append(userBackPack, &api_models.UserBackpack{Gid: int32(v.Gid), Num: 1, PropsType: int32(v.Type)})
		}
	}
	return &api_models.UserBackpackResp{UserBackpack: userBackPack}, nil
}

// 屏蔽操作权限检测
// 1普通用户 2主播 3房管
func ChatRoomPermission(req *api_models.PermissionReq) (*api_models.PermissionResp, error) {
	if req.UserId != req.AnchorId {
		managerUser, err := db_live.GetLiveRoomManagerParam(map[string]interface{}{"mgrid": req.UserId})
		if err != nil {
			return &api_models.PermissionResp{Role: 1}, err
		}
		if managerUser.Id < 1 {
			return &api_models.PermissionResp{Role: 1}, fmt.Errorf("管理员ID不存在")
		}
		if managerUser.Anchorid != 0 && managerUser.Anchorid != int(req.AnchorId) { //不是超管和该房间管理
			return &api_models.PermissionResp{Role: 1}, fmt.Errorf("您没有当前房间的管理权限")
		}
	}

	if req.UserId == req.AnchorId {
		return &api_models.PermissionResp{Role: 2}, nil
	}

	return &api_models.PermissionResp{Role: 3}, nil
}
